package io.wilson.demo.shiro;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.wilson.demo.domain.entity.UserInfo;
import io.wilson.demo.mapper.UserInfoMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component("authorizer")
public class UserRealm extends AuthorizingRealm {
    @Resource
    private UserInfoMapper userInfoMapper;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        UserInfo userInfo = userInfoMapper.selectOne(Wrappers.<UserInfo>lambdaQuery()
                .eq(UserInfo::getUsername, token.getUsername()));
        String password = new String(token.getPassword());
        if (userInfo == null || !password.equals(userInfo.getPassword())) {
            throw new AccountException("用户名密码不匹配");
        }
        return new SimpleAuthenticationInfo(token.getPrincipal(), password, getName());
    }

    /**
     * shiro缓存用户角色，ehcache缓存角色权限。
     * shiro鉴权时获取用户角色，再根据角色的权限码列表到ehcache缓存里查询
     * 用户角色所拥有的所有权限是否有与当前操作匹配的，权限变更后刷新对应的权限缓存。
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

}
